#include "SecurityAuditor.h"
#include <iostream>
#include <fstream>
#include <ctime>
#include <iomanip>
#include <stdexcept>
#include <filesystem>
#include <sstream>

namespace fs = std::filesystem;
using json = nlohmann::json;

// 事件类型转字符串
std::string SecurityAuditor::eventTypeToString(AuditEventType type) {
    switch(type) {
        case AuditEventType::AUTHENTICATION_SUCCESS: return "authentication_success";
        case AuditEventType::AUTHENTICATION_FAILURE: return "authentication_failure";
        case AuditEventType::DATA_ACCESS: return "data_access";
        case AuditEventType::CONFIGURATION_CHANGE: return "configuration_change";
        case AuditEventType::SYSTEM_EVENT: return "system_events";
        case AuditEventType::ALARM_TRIGGERED: return "alarm_triggered";
        case AuditEventType::ALARM_CLEARED: return "alarm_cleared";
        default: return "unknown_event";
    }
}

// 获取当前时间戳
std::string SecurityAuditor::getCurrentTimestamp() {
    auto now = std::chrono::system_clock::now();
    std::time_t now_time = std::chrono::system_clock::to_time_t(now);
    std::tm local_tm = *std::localtime(&now_time);
    
    std::stringstream ss;
    ss << std::put_time(&local_tm, "%Y-%m-%dT%H:%M:%S");
    return ss.str();
}

// 构造函数
SecurityAuditor::SecurityAuditor(const std::string& configPath) : isEnabled(false) {
    // 读取安全配置文件
    std::ifstream configFile(configPath);
    if (!configFile.is_open()) {
        std::cerr << "无法打开安全配置文件: " << configPath << std::endl;
        return;
    }
    
    try {
        json config;
        configFile >> config;
        
        // 提取审计日志配置
        if (config.contains("audit_logging")) {
            auto auditConfig = config["audit_logging"];
            isEnabled = auditConfig.value("enabled", false);
            // 修改为当前目录下的logs子目录
            logPath = "logs/audit.log";
            logLevel = auditConfig.value("log_level", "info");
        }
    } catch (const std::exception& e) {
        std::cerr << "解析安全配置文件失败: " << e.what() << std::endl;
    }
}

// 析构函数
SecurityAuditor::~SecurityAuditor() {
    if (logFile.is_open()) {
        logFile.close();
    }
}

// 初始化审计器
bool SecurityAuditor::initialize() {
    if (!isEnabled) {
        std::cout << "审计日志功能已禁用" << std::endl;
        return true;
    }
    
    try {
        // 创建logs目录（如果不存在）
        if (!fs::exists("logs")) {
            fs::create_directory("logs");
        }
        
        // 打开日志文件（追加模式）
        logFile.open(logPath, std::ios::app);
        if (!logFile.is_open()) {
            std::cerr << "无法打开审计日志文件: " << logPath << std::endl;
            return false;
        }
        
        // 写入启动日志
        logEvent(AuditEventType::SYSTEM_EVENT, "system", "安全审计服务已启动");
        return true;
    } catch (const std::exception& e) {
        std::cerr << "初始化审计器失败: " << e.what() << std::endl;
        return false;
    }
}

// 检查日志级别
bool SecurityAuditor::shouldLog(const std::string& level) {
    // 简化的日志级别检查
    std::map<std::string, int> levelMap = {
        {"debug", 0},
        {"info", 1},
        {"warn", 2},
        {"error", 3},
        {"fatal", 4}
    };
    
    auto currentLevel = levelMap.find(logLevel);
    auto targetLevel = levelMap.find(level);
    
    if (currentLevel == levelMap.end() || targetLevel == levelMap.end()) {
        return true; // 默认记录所有事件
    }
    
    return targetLevel->second >= currentLevel->second;
}

// 记录审计事件
void SecurityAuditor::logEvent(AuditEventType type, const std::string& user, const std::string& details) {
    if (!isEnabled || !logFile.is_open()) {
        return;
    }
    
    std::lock_guard<std::mutex> lock(logMutex);
    
    try {
        json logEntry;
        logEntry["timestamp"] = getCurrentTimestamp();
        logEntry["event_type"] = eventTypeToString(type);
        logEntry["user"] = user;
        logEntry["details"] = details;
        
        logFile << logEntry.dump() << std::endl;
        logFile.flush(); // 确保日志立即写入文件
    } catch (const std::exception& e) {
        std::cerr << "写入审计日志失败: " << e.what() << std::endl;
    }
}